<?php
/**
 * Created by PhpStorm.
 * User: 阿沁
 * Date: 2024/3/20
 * Time: 14:11
 * SOURCE: 中国大陆工时规管现况（标准工时）：
 *              一天工作时间为8小时，平均每周工时不超过40小时;
 *              加班上限为一天3小时及一个月36小时，逾时工作薪金不低于平日工资的150％。
 *              而一周最高工时则为48小时。平均每月计薪天数为21.75天。
 * TO: 我是阿沁,健康撸代码,拒绝通宵。
 * 版权所有: © 2024-2030 阿沁
 * WARNING: 未经本人许可, 禁止一切商用
 * CLASS: < Common.php >
 */

namespace app\common;


use app\model\User;
use app\model\UserLayer;
use app\model\UserVipChild;
use app\model\VipOrders;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use think\facade\Cache;
use think\facade\Config;
use Throwable;

class Common
{
	public static function findParent(User $user): User|bool
	{
		// 如果当前节点满足条件，直接返回当前节点
		if ($user->parent) {
			$vip_child = UserVipChild::where(['user_id' => $user->parent->id])->column('child_id');
			if (!in_array($user->id, $vip_child)&&$user->parent->level>=3) {
				return $user->parent;
			}
			return self::findParent($user->parent);
		}
		return false;
		
		
	}
	
	/**
	 * 获取小程序access_token
	 * @throws Throwable
	 */
	public static function getWechatAccessToken()
	{
		return Cache::remember('mini_access_token', function () {
			$client = new Client();
			$appid = Config::get('wechat.wechat_mini.appid');
			$secret = Config::get('wechat.wechat_mini.secret');
			//获取接口调用凭据
			$wechattoken = $client->post("https://api.weixin.qq.com/cgi-bin/token", [
				'query' => [
					'appid' => $appid,
					'secret' => $secret,
					'grant_type' => 'client_credential',
				]
			]);
			$wechattoken = json_decode($wechattoken->getBody()->getContents());
			if (!isset($wechattoken->access_token)) {
				throw new Exception('凭据接口调用失败');
			}
			return $wechattoken->access_token;
		}, 7000);
	}
	
	/**
	 * 获取微信openid
	 * @param $minicode
	 * @return mixed
	 * @throws Exception|GuzzleException
	 */
	public static function getWechatOpenid($minicode)
	{
		$client = new Client();
		$appid = Config::get('wechat.wechat_mini.appid');
		$secret = Config::get('wechat.wechat_mini.secret');
		$login = $client->get("https://api.weixin.qq.com/sns/jscode2session", [
			'query' => [
				'appid' => $appid,
				'secret' => $secret,
				'js_code' => $minicode,
				'grant_type' => 'authorization_code'
			]
		]);
		$wechat = json_decode($login->getBody()->getContents());
		if (!isset($wechat->openid)) {
			throw new \Exception($wechat->errmsg);
		}
		return $wechat->openid;
	}
	
}